package mapper

import (
	"fmt"
	"gorm.io/gorm"
	"time"
	"ylb/config"
	"ylb/entity"
	"ylb/tool"
)

type JobMapper struct {
	DB *gorm.DB
}

func NewJobMapper() JobMapper {
	mapper := JobMapper{}
	mapper.DB = tool.GetGormConnection(config.GetDBUrlConfig())
	return mapper
}

func (mapper *JobMapper) SelectAllByUserId(userId uint) []entity.Job {
	var jobList []entity.Job
	mapper.DB.Where("user_id = ?", userId).Order("expire").Find(&jobList)
	return jobList
}
func (mapper *JobMapper) SelectAllByCollect(userId uint) []entity.Job {
	var jobList []entity.Job
	mapper.DB.Where("user_id = ? and collect = ?", userId, 1).Order("expire").Find(&jobList)
	return jobList
}

func (mapper *JobMapper) SelectAllByLimitTime(userId uint, start time.Time, end time.Time) []entity.Job {
	var jobList []entity.Job
	mapper.DB.Where("user_id = ? and expire >= ? and expire <= ?", userId, start, end).Order("expire").Find(&jobList)

	return jobList
}

func (mapper *JobMapper) SelectAllByClassifyAndUserId(userId, classify uint) []entity.Job {
	var jobList []entity.Job
	mapper.DB.Where("classify = ? and user_id = ? ", classify, userId).Order("expire").Find(&jobList)
	return jobList
}
func (mapper *JobMapper) SelectAllByLike(like string) []entity.Job {
	var jobList []entity.Job
	mapper.DB.Where("name like ?", "%"+like+"%").Order("expire").Find(&jobList)
	return jobList
}
func (mapper *JobMapper) InsertOne(job *entity.Job) int64 {
	tx := mapper.DB.Create(job)
	if tx.Error != nil {
		fmt.Println(tx.Error.Error())
	}
	return tx.RowsAffected
}
func (mapper *JobMapper) DeleteOne(id uint) int64 {
	//逻辑删除 / 软删除
	tx := mapper.DB.Delete(&entity.Job{
		Model: gorm.Model{
			ID: id,
		},
	})
	return tx.RowsAffected
}
func (mapper *JobMapper) UpdateJob(jobId int, jobMap map[string]interface{}) int64 {

	tx := mapper.DB.Model(&entity.Job{}).Where("ID = ?", jobId).Updates(jobMap)
	return tx.RowsAffected

}
